<?php

namespace App\Imports;

use App\Models\Hero;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Row;

class HerosImport implements OnEachRow, WithBatchInserts, WithChunkReading
{
    public function getCsvSettings(): array
    {
        return [
            'input_encoding' => 'utf-8'
        ];
    }

    public function onRow(Row $row)
    {
        $rowIndex = $row->getIndex();
        $row      = $row->toArray();

        foreach ($row as $key => $item) {
            $row[$key] = trim($item);
        }

        if (!isset($row[0]) || !is_numeric($row[0]) || empty($row[10])) {
            return null;
        }
        if (empty($row[8]))
            $row[8] = '无名';

        if (!empty($row[13])) {
            $enter_date = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[13]));
            $enter_date = (string)$enter_date;
            $enter_date = substr($enter_date, 0, 10);
        } else {
            $enter_date = null;
        }

        if (!empty($row[7])) {
            $buy_date = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[7]));
            $buy_date = (string)$buy_date;
            $enter_date = substr($buy_date, 0, 10);
        } else {
            $buy_date = null;
        }

        $hero = Hero::where('username', $row[10])->where('contact_name', $row[8])->dontRemember()->first();

        $data = [
            'username'     => $row[10],
            'username2'    => $row[11],
            'area' => $row[2],
            'row' => $row[3],
            'seat' => $row[4],
            'garden_name' => $row[1],
            'status' => $row[5],
            'type' => $row[6],
            'buy_date' => $buy_date,
            'contact_name' => $row[8],
            'contact_relation' => $row[9],
            'burail_name' => $row[12] ?? null,
            'enter_date' => $enter_date
        ];
        if ($hero) {
            \Log::error("import-update" . json_encode($row));
            Hero::where('id', $hero->id)->update($data);
            Hero::deleteCachePk($hero->id);
        } else {
            if (!Hero::create($data)) {
                \Log::error("import-error" . json_encode($row));
            }
        }
    }

    public function batchSize(): int
    {
        return 10;
    }

    public function chunkSize(): int
    {
        return 10;
    }
}
